<template>
    <!-- 支付弹层 -->
    <view class="zz-popPay_20200805">

        <!-- 选择支付方式 -->
        <notice
            v-if="type=='10'||orderInfo.status==100"
            :visible="selectPayTypePop"
            :showCloseIcon="showCloseIcon"
            @close="closeTypesFn">
            <!-- 标题 -->
            <template slot="header">
                <!-- 微信支付 + 余额支付 -->
                <view 
                    v-if="payStatus==='0'"
                    class="zz-mb74">{{payInfo[payStatus].title}}</view>
                <!-- 确认用余额支付 -->
                <view 
                    v-if="payStatus==='1'"
                    class="zz-mb60">{{payInfo[payStatus].title}}</view>
                <!-- 支付成功 -->
                <view 
                    v-if="payStatus==='2'"
                    class="zz-mb44">{{payInfo[payStatus].title}}</view>
                <!-- 余额不足，支付失败 -->
                <view 
                    v-if="payStatus==='3'"
                    class="zz-mb60">{{payInfo[payStatus].title}}</view>
                <!-- 支付失败 -->
                <view 
                    v-if="payStatus==='4'"
                    class="zz-mb44">{{payInfo[payStatus].title}}</view>
            </template>
            <!-- 选择支付方式 -->
			<template slot="body">
				<view class="zz-flex zz-ff-cw zz-ai-c">
					<!-- 微信支付 + 余额支付 -->
					<view v-if="payStatus==='0'">
                        <!-- :style="payMoneyType===index&&themeStyles.btnSelected" -->
						<view 
							v-for="(item,index) in payTypesData"
							:key="index"
                            :style="[{'background-color':`${themeStyles.mainColor}`},payMoneyType===index&&themeStyles.btnSelected]"
							class="zz-btn zz-btn_paytype zz-flex zz-jc-c zz-ai-c"
                            :class="{'zz-mb74':index===0}"
							@click="selectPayMoneyTypeAfter(index,item)">
							<text
								class="colorFFF"
								:class="item.iconClass"></text>
							<view class="zz-ml24 fs32 lh44 colorFFF">{{item.title}}</view>
						</view>
					</view>
					<!-- 确认用余额支付 -->
					<view v-if="payStatus==='1'">
						<view class="fs32 lh44 color333 zz-mb44">
							<text>当前余额：</text>
							<text>{{balance}}</text>
						</view>
						<view class="zz-flex fs32 lh44 color333 zz-mb72">
							<text>本次支付：</text>
							<view
                                v-if="orderInfo.totalFeeStr"
								:style="themeStyles.textMainColor"
								class="price-total-content"
							>
								<text class="price">{{ orderInfo.totalFeeStr }}</text>
							</view>
                            <view
                                v-else
								:style="themeStyles.textMainColor"
								class="price-total-content"
							>
								<text class="price">{{ totalFee[0] }}</text>
								<text>.</text>
								<text class="decimal">{{
									totalFee[1] || "00"
								}}</text>
							</view>
						</view>
					</view>
					<!-- 支付成功 -->
					<view v-if="payStatus==='2'">
						<view class="zz-flex zz-jc-c lh156 zz-mb64">
							<text 
								:style="themeStyles.textMainColor"
								class="fs156 template__icon template_icon-pay-suc"></text>
						</view>
					</view>
					<!-- 余额不足，支付失败 -->
					<view v-if="payStatus==='3'">
						<view class="zz-mb72">
							<!-- <text 
								:style="themeStyles.textMainColor"
								class="fs128 template__icon template_icon-colse"></text> -->
                            <view class="zz-flex zz-jc-c fs32 lh44 color333 zz-mb44"><text>当前余额：</text>{{balance}}</view>
                            <view class="zz-flex fs32 lh44 color333">
                                <text>本次支付：</text>
                                <view
                                    v-if="orderInfo.totalFeeStr"
                                    :style="themeStyles.textMainColor"
                                    class="price-total-content"
                                    >
                                    <text class="price">{{ orderInfo.totalFeeStr }}</text>
                                </view>
                                <view
                                    v-else
                                    :style="themeStyles.textMainColor"
                                    class="price-total-content"
                                    >
                                    <text class="price">{{ orderInfo.totalFee[0] }}</text>
                                    <text>.</text>
                                    <text class="decimal">{{
                                        orderInfo.totalFee[1] || "00"
                                    }}</text>
                                </view>
                            </view>
						</view>
					</view>
                    <!-- 支付失败 -->
                    <view v-if="payStatus==='4'">
                        <view class="zz-flex zz-jc-c lh156 zz-mb64">
							<text 
								:style="themeStyles.textMainColor"
								class="fs156 template__icon template_icon-colse"></text>
						</view>
                    </view>
				</view>
			</template>
			<!-- 按钮 -->
			<template slot="footer">
				<!-- 确认用余额支付 -->
				<view 
					v-if="payStatus==='1'">
					<view 
					@click="confirmBalancePay"
					:style="themeStyles.btnPrimary"
					class="zz-btn zz-btn_large zz-mb24">确定支付</view>
					<view 
						@click="backToPayTypeSelect"
						class="zz-btn zz-btn_large">返回</view>
				</view>
				<!-- 支付成功 -->
				<view v-if="payStatus==='2'">
					<view 
					@click="paySuccessAfter"
					:style="themeStyles.btnPrimary"
					class="zz-btn zz-btn_large">确定</view>
				</view>
				<!-- 余额不足，支付失败 -->
				<view 
					v-if="payStatus==='3'">
					<!-- <view 
                    @click="reUseWechatPay"
					:style="themeStyles.btnPrimary"
					class="zz-btn zz-btn_large zz-mb24">微信支付</view>
					<view 
                        @click="goToRechargePage"
						class="zz-btn zz-btn_large">立即充值</view> -->
                    <view 
					    @click="reChargeNow"
					    :style="themeStyles.btnPrimary"
					    class="zz-btn zz-btn_large zz-mb24">立即充值</view>
					<view 
						@click="backToPayTypeSelect"
						class="zz-btn zz-btn_large">返回</view>
				</view>
                <!-- 支付失败 -->
                <view v-if="payStatus==='4'">
					<view 
					@click="payFailAfter"
					:style="themeStyles.btnPrimary"
					class="zz-btn zz-btn_large">确定</view>
				</view>
			</template>
        </notice>
        <!-- 二维码核销 -->
        <notice
            v-if="type=='15'&&orderInfo.status==250"
            width="686"
            height="760"
            :nopd="true"
            :visible="selectPayTypePop"
            :showCloseIcon="false"
            @close="closeTypesFn">
            <!--  -->
            <template slot="body">
                <view class="qrcode-area_title zz-flex zz-ai-c">
                    <text 
                        class="fs36 lh42 color333 template__icon template_icon-pay"></text>
                    <view class="zz-ml20 fs28 lh28 color333">请展示给工作人员核销</view>
                </view>
                <view class="qrcode-area_qr">
                    <image class="zz-img-fit" :src="qrCodeSrc"></image> 
                </view>    
            </template>    
        </notice>
    </view>
</template>
<script>
/*  */
const app = getApp();
/* mixin */
import socketMixin from "@/mixins/socket";
/* api */
import { 
    _getQR,  //核销二维码
    _socketUrl  //socket地址
} from "@/lib/api/orderServer/order";
/* 获取钱包详情 */
import { _getWallet } from "@/lib/api/walletServer/info";
/* 获取订单金额和余额 */
import {
    _orderMoney  //获取订单金额和余额信息
} from "@/lib/api/orderServer/order";
/* 弹窗 */
import notice from "@/components/notice";
/*  */
import { mapState,mapMutations } from "vuex"; 
export default {
    mixins:[
        socketMixin
    ],
    components:{
        notice
    },
    props:{
        /* 类型（选择付款 or 到店二维码核销） */
        type:{
            type:String,
            default:"10"
        },
        /* 显示隐藏弹层 */
        showPopPay:{
            type:Boolean,
            default:false
        },
        /* 订单信息信息 */
        orderInfo:{
            type:Object,
            default(){
                return {
                    status:"",
                    totalFee:[]
                };
            }
        }
    },
    watch:{
        showPopPay(val){
           //console.log(val);
            if(val){
               this.open();
            }else{
               this.close();
            }
        } 
    },
    computed:{
        ...mapState("wallet", ["balance", "integral"]),
        //隐藏关闭按钮
        showCloseIcon(){
            return false;
        }
    },
    data(){
        return {
            /* 20200805 */
            showPopWrap:true,  //
			selectPayTypePop:false,  //选择支付方式弹层
			payMoneyType:"",  //选择的支付方式
			payTypesData:[
				{
					title:"微信支付",
					type:0,
					iconClass:"template__icon template_icon-wechat fs76"
				},
				{
					title:"余额支付",
					type:1,
					iconClass:"template__icon template_icon-balance fs76"
				}
			],
			payInfo:{
				"0":{
					title:"请选择付款方式"
				},
				"1":{
					title:"余额支付"
				},
				"2":{
					title:"支付成功"
				},
				"3":{
					title:"余额不足，支付失败"
				},
				"4":{
					title:"支付失败"
				}
			},
			payStatus:"0",  // 0:选择支付方式  1:确认余额支付  2:支付成功  3:余额不足，支付失败 4:支付失败
            /*  */
            orderId:"",  //订单id
            orderMoneyData:{}, //订单金额和余额信息
            /* 关闭弹层根据状态执行对应操作 */
            closeTypes:{
                //"请选择付款方式"
               "0"(){
                    //  route: "pages/user/pages/order/createOrder"
                    //  console.log(getCurrentPages());
                    //console.log(this.orderInfo);
                    const curPage = getCurrentPages().pop();
                    this.closePayTypePop();
                    //创建订单页面
                    if(curPage.route==="pages/user/pages/order/createOrder"){
                        //已创建订单-取消支付
                        this.reLaunchOrderList();
                    }
                },
                //"余额支付"
				"1"(){
                    this.payFailAfter();
                },
                //"支付成功"
				"2"(){
                    this.paySuccessAfter();
                },
                //"余额不足，支付失败"
				"3"(){
                    this.payFailAfter();
                },
                //"支付失败"
				"4"(){
                    this.payFailAfter();
                }
            },
            /* 余额支付--要支付的金额 */
            totalFee:[] 
        };
    },
    methods:{
        ...mapMutations("wallet", ["setBalance", "setIntegral"]),
        /* 
            自定义方法:
            @select-pay-type:  选择支付方式触发
            @payBefore:  支付之前
            @payFn:  支付方法
            @paySuccessAfter:  支付成功后，点击确定
            @payFailAfter:   支付失败后，点击确定
        */
       /* 
        跳转至订单列表
       */
        reLaunchOrderList(){
            let routeLink = "/pages/user/pages/order/orderList";
            uni.reLaunch({ url: routeLink });
        },
       /* 
            关闭弹层
       */
       closeTypesFn(){
            //console.log(this);
            //console.log(this.payStatus);
            if(this.payStatus){
               (this.closeTypes[this.payStatus])&&(this.closeTypes[this.payStatus].call(this));
            }else{
               this.closePayTypePop();
            }
       },
       /* 
            支付失败后点击确定--重新选择支付方式
       */
        payFailAfter(){
            this.payStatus = "0";
            this.payMoneyType = "";
            this.togglePayTypePop();
            //
            this.$emit("payFailAfter");
        },
        /* 
            选择支付方式之后
        */
        selectPayMoneyTypeAfter(index,item){
           //
           this.payMoneyType = index;
           //
           this.$emit("select-pay-type",this.payMoneyType);
           //选择微信支付
           if(this.payMoneyType===0){
                this.useWechatPay();
           }
           //选择余额支付---显示余额支付确认框
			if(this.payMoneyType===1){
                //
                new Promise((resolve,reject)=>{
                    //获取订单id
                    this.$emit("payBefore","",orderId=>{
                        //console.log(orderId);
                        if(orderId){
                            this.orderId = this.orderInfo.orderId||orderId;
                            resolve();
                        }else{
                            reject(false);
                        }
                    }); 
                }).then(()=>{
                    //获取订单金额和余额数据
                    return _orderMoney({
                        orderId:this.orderId
                    });
                    //console.log(orderMoneyData);
                }).then(res=>{
                    //console.log(res);
                    if(res.data.enough){
                        //余额显示
                        this.totalFee = `${res.data.totalFee}`.split(".");
                        //余额足够--进行余额支付
                        this.payStatus = "1";
                        this.togglePayTypePop();
                    }else{
                        //余额不足时
                        return Promise.reject(res.data);
                    }
                }).catch(err=>{
                    console.log(err);
                    //余额不足
                    if(typeof err === "object"&&err.enough===false){
                        this.payStatus = "3";
                        this.togglePayTypePop();
                        return;
                    }
                    //支付失败
                    if(typeof err === "boolean"&&err===false){
                        this.payStatus = "4";
                        this.togglePayTypePop();
                        return;
                    }
                    //请求出错
                    this.$api.showModal({
                        content:`${err.resultInfo}`
                    })
                });
			}
        },
       /* 
            确认使用余额支付
       */
        confirmBalancePay(){
            new Promise((resolve,reject)=>{
                //
                this.$emit("payFn","",bool=>{
                    console.log("paySuccess",bool);
                    bool?resolve():reject(false);
                });
            }).then(()=>{
                //获取余额
                return _getWallet();
            }).then(res=>{
                console.log(res);
                let {
                    creditTotal = 0,  //积分
                    moneyTotal = 0    //余额
                } = res.data;
                //moneyTotal = 12.5;
                this.setIntegral(creditTotal);
                this.setBalance(this.ZZaddNumZero(moneyTotal));
                //余额支付成功
                this.payStatus = "2";
                return this.togglePayTypePop();
            });
            //
            //余额支付成功???
            //余额支付失败
            //this.payStatus = "3";
            //this.togglePayTypePop();
        },
        /* 
            返回支付方式选择
        */
        async backToPayTypeSelect(){
            //
            this.payStatus = "0";
            //
            this.payMoneyType = "";
            //
            this.$emit("select-pay-type",this.payMoneyType);
            await this.togglePayTypePop();
        },
        /* 
            点击支付成功弹层上的确定
        */
        paySuccessAfter(){
            this.closePayTypePop();
            //
            this.$emit("paySuccessAfter");
        },
        /* 
            使用微信支付 --余额不足时，继续使用微信支付
        */
        useWechatPay(){
            //console.log(this.useWechatPay);
            //
            this.payMoneyType = 0;
            //
            this.$emit("select-pay-type",this.payMoneyType);
            new Promise((resolve,reject)=>{
                //获取订单id
                this.$emit("payBefore","",orderId=>{
                    if(orderId){
                        this.orderId = orderId;
                        resolve();
                    }else{
                        reject(false);
                    }
                }); 
            }).then(()=>{
                //支付
                return new Promise((resolve,reject)=>{
                    this.$emit("payFn","",bool=>{
                        console.log("paySuccess",bool);
                        bool?resolve():reject(false);
                    });
                })
            }).then(()=>{
                //获取余额
                return _getWallet();
            }).then(res=>{
                console.log(res);
                let {
                    creditTotal = 0,  //积分
                    moneyTotal = 0    //余额
                } = res.data;
                //moneyTotal = 12.5;
                this.setIntegral(creditTotal);
                this.setBalance(this.ZZaddNumZero(moneyTotal));
                //支付成功
                this.payStatus = "2";
                return this.togglePayTypePop();
            }).catch(err=>{
                //支付失败
                if(typeof err==="boolean"&&err===false){
                    this.payStatus = "4";
                    this.togglePayTypePop();
                }
            });
        },
        /* 
            余额不足时，使用微信支付
        */
        reUseWechatPay(){
            this.useWechatPay();
        },
        /* 
            余额不足时，跳转至充值页面
        */
        goToRechargePage(){
            //关闭弹窗
            this.closePayTypePop();
            //
            app.globalData.fromPaypopToRecharge = true;
            //
            this.loginNavTo("/pages/user/pages/wallet/recharge")
        },
        /* 
			关闭选择支付方式的弹层
		*/
		closePayTypePop(){
			this.selectPayTypePop = false;
			this.payStatus = "0";
            this.payMoneyType = "";
            //关闭弹窗
            this.$emit("close");
		},
		/* 
			切换显示选择支付方式的弹层
		*/
		togglePayTypePop(){
			this.selectPayTypePop = false;
			return Promise.resolve().then(()=>{
				this.selectPayTypePop = true;
			});
        },
        /* 
           打开选择弹层 
        */
        open(){
            this.selectPayTypePop = true;
            //到店订单且已支付--核销二维码
            //console.log(this.orderInfo);
            //到店订单-已支付,待到店--核销二维码
            const { status, type } = this.orderInfo;
            //console.log(status);
            //console.log(type);
            //return;
            if(this.type==='15'&&status==250){
                //this.$api.showToast(`${_socketUrl}${this.orderInfo.orderId}`);
                this.socketUrl = `${_socketUrl}${this.orderInfo.orderId}`;
                console.log(this.socketUrl);
                this.initSocket(
                    this.socketUrl,
                    ()=>{
                        return `${_getQR()}${this.orderInfo.orderId}`
                    },
                    data=>{
                    //核销之后
                    this.close();
                    let routeLink = "/pages/user/pages/order/orderList";
                    uni.reLaunch({ url: routeLink });
                    /* if(data.type=="10"){
                        //扫码支付成功
                        if(data.result){
                            //
                            this.loginNavTo(`/pages/user/pages/wallet/paySuccess?info=${res.data}`);
                        }else{
                            //支付失败
                            this.noticeData = null;
                            this.noticeData = data;
                            //
                            this.noticeVisible = true;
                        }
                    } */
                });
            }
        },
        /* 
            关闭选择弹层
        */
        close(){
            //到店订单-已支付,待到店--核销二维码
            const { status, type } = this.orderInfo;
            if(this.type==='15'&&status==250){
               this.closeSocket();
            }
            this.closePayTypePop(); 
        }
    }
}
</script>
<style lang="scss">
.zz-popPay_20200805 {
    .qrcode-area {
        &_title {
            height:92rpx;
            padding:28rpx 24rpx;
            background-color:rgba(245,245,245,1);
        }
        &_qr {
            width:520rpx;
            height:520rpx;
            margin:64rpx 82rpx 0rpx;
        }
    }
}
</style>